package com.ck.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.ck.cache.RedisCacheDao;
import com.ck.chuangke.service.CkCompanyService;
import com.ck.common.service.UserService;
import com.ck.constant.BusinessConstant;
import com.ck.constant.CacheConstant;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.jwt.JwtUtil;
import com.ck.model.common.Company;
import com.ck.model.common.User;
import com.ck.model.common.sys.JsonResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dxy
 * @date 2018/7/4 19:24
 */
@Controller
@RequestMapping(value = "/web")
public class WebController {
    private static Logger logger = LoggerFactory.getLogger(WebController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private CkCompanyService ckCompanyService;
    @Autowired
    private RedisCacheDao redisCacheDao;

    /**
     * 跳转至登录界面
     */
    @RequestMapping("/login")
    public String goLogin() {
        return "common/login";
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping("/doLogin")
    public Object login(String userName, String password, HttpServletRequest request) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, DigestUtils.md5Hex(password));
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            //账户不存在
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户不存在");
        } catch (IncorrectCredentialsException e) {
            //密码错误
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
        }
        User user = userService.getUserByUserName(userName);
        if (user == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户不存在");
        }
        if (BusinessConstant.STATUS_DISABLE == user.getStatus()) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户已被禁用，请联系管理员");
        }
        //验证密码
        if (StringUtils.isBlank(password)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空");
        }
        String oldPassword = user.getPassword();
        String md5Password = DigestUtils.md5Hex(password);
        if (!md5Password.equals(oldPassword)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "密码错误");
        }
        //验证通过，将用户放入sessoin中
        request.getSession().setAttribute(RequestConstant.SESSION_KEY_USER, user);
        String token = "";
        //如果已经登录过，则使用已有的token，未登录则生成新的token
        Object tokenRedis = redisCacheDao.getCache(CacheConstant.CK_TOKEN_USER_MAPPING, user.getUserName());
        if (null != tokenRedis) {
            token = tokenRedis.toString();
        } else {
            token = JwtUtil.sign(userName, md5Password);
        }
        redisCacheDao.putCache(CacheConstant.CK_TOKEN_CACHE_NAME, token,
                JSONObject.toJSONString(user), CacheConstant.CACHE_EXPIRE_SECONDS);
        redisCacheDao.putCache(CacheConstant.CK_TOKEN_USER_MAPPING, userName, token, CacheConstant.CACHE_EXPIRE_SECONDS);
        return new JsonResponse(ResponseConstant.CODE_SUCCESS, token, "登录成功");
    }

    /**
     * 跳转至index.html
     */
    @RequestMapping(value = "/goIndex")
    public String goIndex(HttpServletRequest request, Model model) {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        // 用户类型（0：创客用户；1：商家用户）
        int type = loginUser.getType();
        model.addAttribute("type", type);
        model.addAttribute("userName", loginUser.getUserName());
        // 如果是商家登录 则显示商家的logo 和 商家名字
        if (1 == type) {
            String companyCode = loginUser.getCompanyCode();
            Company company = ckCompanyService.getCompanyInfoByCompanyCode(companyCode);
            if (company == null) {
                company = new Company();
            }
            model.addAttribute("company", company);
            model.addAttribute("title", company.getCompanyName() + "信发系统");
        } else {
            model.addAttribute("title", "创客信发系统");
        }
        return "common/index";
    }

    /**
     * 注销登录
     */
    @RequestMapping(value = "/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            Object userSession = request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            if (null != userSession) {
                User u = (User) userSession;
                Object tokenRedis = redisCacheDao.getCache(CacheConstant.CK_TOKEN_USER_MAPPING, u.getUserName());
                if (null != tokenRedis) {
                    redisCacheDao.deleteByKey(CacheConstant.CK_TOKEN_CACHE_NAME, tokenRedis);
                    redisCacheDao.deleteByKey(CacheConstant.CK_TOKEN_USER_MAPPING, u.getUserName());
                }
                //从session中移除用户
                request.getSession().removeAttribute(RequestConstant.SESSION_KEY_USER);
            }
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            //重定向到登录界面
            response.sendRedirect(request.getContextPath() + "/web/login");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("WebController logout 注销登录失败：" + e.getMessage());
        }
    }

}
